import cv2
import numpy as np
# 读取图像
img = cv2.imread('3.png')
# # 定义颜色范围
# lower_range = np.array([0, 128, 128])
# upper_range = np.array([0, 128, 128])
# # 创建掩膜
# mask = cv2.inRange(img, lower_range, upper_range)
# # 计算像素数量
# total_pixels = mask.shape[0] * mask.shape[1]
# color_pixels = cv2.countNonZero(mask)
# # 计算颜色占比
# color_ratio = color_pixels / total_pixels
# print("像素数量",color_pixels)
# print("颜色占比：", color_ratio)

def checkNumOfPixels(imagePath,lower_range,upper_range):
    img = cv2.imread(imagePath)
    # # 定义颜色范围
    # lower_range = np.array([0, 128, 128])
    # upper_range = np.array([0, 128, 128])
    # 创建掩膜
    mask = cv2.inRange(img, lower_range, upper_range)
    # 计算像素数量
    total_pixels = mask.shape[0] * mask.shape[1]
    color_pixels = cv2.countNonZero(mask)
    return color_pixels


pred_saved_path="12.png"
# 危害状
lower_range = np.array([0, 128, 128])
upper_range = np.array([0, 128, 128])
weihaizhuangNum = checkNumOfPixels(pred_saved_path,lower_range,upper_range)
#叶片
lower_range = np.array([0, 128, 0])
upper_range = np.array([0, 128, 0])
leafNum = checkNumOfPixels(pred_saved_path, lower_range, upper_range)
zhanbi=float(weihaizhuangNum)/(float(weihaizhuangNum)+float(leafNum))
print(zhanbi)

